#!/usr/bin/env bash
# deepdive-mark -- Marks state of something to do
#
# To assume certain TARGETs are already done:
# > deepdive mark done  TARGET...
#
# To mark certain TARGETs as new, so the ones depending on it can be repeated:
# > deepdive mark all-new  TARGET...
# > deepdive mark     new  TARGET...
#
# To mark TARGETs shall be done again:
# > deepdive mark todo  TARGET...
# To mark TARGETs shall be done again including their dependencies:
# > deepdive mark todo-from-scratch  TARGET...
#
# To cancel the latest changes made to the state of TARGETs:
# > deepdive mark restore  TARGET...
##
set -eu

[[ $# -gt 0 ]] || usage "$0" "Specify what to mark"
[[ $# -gt 1 ]] || usage "$0" "No TARGET specified"

State=$1; shift
case $State in
    "done"|new|all-new|todo|todo-from-scratch|restore) ;;
    "") ;;
    *) error "$State: Unknown state. Can mark as 'done', 'new', 'all-new', 'todo', or 'todo-from-scratch' only, or 'restore'"
esac
. resolve-args-to-do.sh

case $State in
    "done")
        # XXX cannot use make's --touch as it doesn't ensure parent directories exist
        make -C "$DEEPDIVE_APP"/run TOUCH='mkdir -p $(@D) && touch $@' --silent "$@"
        ;;

    new)
        cd "$DEEPDIVE_APP"/run
        touch "$@"
        ;;

    all-new)
        # XXX cannot use make's --touch as it doesn't ensure parent directories exist
        make -C "$DEEPDIVE_APP"/run TOUCH='mkdir -p $(@D) && touch $@' --silent --always-make "$@"
        ;;

    todo|restore)
        cd "$DEEPDIVE_APP"/run
        # for non process/* targets, e.g., data/*, also marking their dependencies as undone
        eval 'set -- "$@" '"$(
            targets=${*%.done} jq -r <compiled/config.json '
                .deepdive_.execution.dependencies |
                .[ env.targets | splits(" ") | select(startswith("process/") | not)
                ][] | "\(.).done" | @sh
            ' | tr '\n' ' ')"
        case $State in
            todo)      reset_timestamp "$@" ;;
            restore) restore_timestamp "$@" ;;
        esac
        ;;

    todo-from-scratch)
        make -C "$DEEPDIVE_APP"/run --silent "${@/.done/.reset}" RESET=reset_timestamp
        ;;

esac
